package org.dftproject.gedcom.core;

import java.util.LinkedList;
import java.util.List;

import org.dftproject.genesis.data.genealogy.GenealogyConstants;
import org.dftproject.genesis.data.genealogy.IPerson;
import org.dftproject.genesis.data.genealogy.IRole;

public class Family {
	
	private final IGedcom gedcom;
	private final Line record;
	
	private Event marriage;
	
	public Family(IGedcom gedcom, Line record) {
		this.gedcom = gedcom;
		this.record = record;
	}

	public IPerson getFather() {
		List<Line> lines = record.getChildren("HUSB");
		if (!lines.isEmpty()) {
			String id = lines.iterator().next().getPointer();
			if (id != null)
				return gedcom.getPerson(id);
		}
		
		return null;
	}

	public IPerson getMother() {
		List<Line> lines = record.getChildren("WIFE");
		if (!lines.isEmpty()) {
			String id = lines.iterator().next().getPointer();
			if (id != null)
				return gedcom.getPerson(id);
		}
		
		return null;
	}

	public IPerson[] getChildren() {
		List<IPerson> children = new LinkedList<IPerson>();

		for (Line line : record.getChildren("CHIL")) {
			String id = line.getPointer();
			IPerson child = gedcom.getPerson(id);
			if (child != null)
				children.add(child);
		}
		
		return children.toArray(new IPerson[0]);
	}

	public Event getMarriage() {
		if (marriage == null) {
			List<Line> lines = record.getChildren("MARR");
			if (!lines.isEmpty()) {
				marriage = new Event(lines.iterator().next());
				
				lines = record.getChildren("HUSB");
				if (!lines.isEmpty()) {
					String id = lines.iterator().next().getPointer();
					IRole role = new Role(GenealogyConstants.Spouse, gedcom, id, marriage);
					marriage.addRole(role);
				}
				
				lines = record.getChildren("WIFE");
				if (!lines.isEmpty()) {
					String id = lines.iterator().next().getPointer();
					IRole role = new Role(GenealogyConstants.Spouse, gedcom, id, marriage);
					marriage.addRole(role);
				}
			}
			
			/*lines = record.getChildren("DIV");
			if (!lines.isEmpty()) {
				divorce = new Event(lines.iterator().next());
				
				lines = record.getChildren("HUSB");
				if (!lines.isEmpty()) {
					String id = lines.iterator().next().getPointer();
					IRole role = new Role(GenealogyConstants.Spouse, gedcom, id, divorce);
					divorce.addRole(role);
				}
				
				lines = record.getChildren("WIFE");
				if (!lines.isEmpty()) {
					String id = lines.iterator().next().getPointer();
					IRole role = new Role(GenealogyConstants.Spouse, gedcom, id, divorce);
					divorce.addRole(role);
				}
			}*/
		}
		return marriage;
	}

}
